const app = getApp();
let tool = require('../../utils/tool.js');
let util = require('../../utils/util.js');

Page({
  data: {
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    year: 0,
    month: 0,
    week: ['日', '一', '二', '三', '四', '五', '六'],
    dateArr: [],
    isToday: 0,
    isTodayWeek: false,
    todayIndex: 0,
    confirmles: [], //審核中的申請
    confirmed: [], //审核通过的申请
    justsub: [], //仅仅提交了的约课
    yuekearr: [],
    date: '2019-01-01 00:00',
    disabled: false, //设置是否能点击 false可以 true不能点击
    startDate: 2019,
    endDate: 2023,
    placeholder: '请选择时间',
    yuekeDataArr: new Array(), //选择好的约课时间[[starttime,endtime]]
    curStartime: '',
    curEndtime: '',
    curStarday: '',
    curEndday: '',
    classsc: 7200, //每次选课的最大时间
    classtotal: {}, //已选课程数量每天最多两次
    plusswitch: false,
    selectDate: false,
    pageName: '约课',
    navH: app.globalData.navHeight,
    startTime: '00:00', //开始时间
    endTime: '00:00', //结束时间
    paramDate: '', //选定的日期
    isBeforToday: true, //是否在今天之前

  },
  onLoad: function(option) {
    console.log(option);
    var curdate = util.formatDate(new Date());
    console.log("默认设置今天的时间为选定的日期", curdate)
    this.setData({
      paramDate: curdate
    });

    this.nowdata(parseInt(option.month), parseInt(option.year));
    this.getData();
    this.nowdata();
    // this.getList();
    wx.showModal({
      title: '温馨提示',
      content: "请先选择约课的日期",
      showCancel: false,
    });
  },



  nowdata: function() {
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    this.dateInit();
    this.setData({
      year: year,
      month: month,
      isToday: '' + year + month + now.getDate()
    })

  },
  dateInit: function(setYear, setMonth) {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let dateArr = []; //需要遍历的日历数组数据
    let arrLen = 0; //dateArr的数组长度
    let now = setYear ? new Date(setYear, setMonth) : new Date();
    let year = setYear || now.getFullYear();
    let nextYear = 0;
    let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
    let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
    let startWeek = new Date(year + '/' + (month + 1) + '/' + 1).getDay(); //目标月1号对应的星期
    let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
    let obj = {};
    let num = 0;
    //设置timepicker的年份范围
    this.setData({
      startDate: year,
      endDate: year + 1
    });
    if (month + 1 > 11) {
      nextYear = year + 1;
      dayNums = new Date(nextYear, nextMonth, 0).getDate();
    }
    arrLen = startWeek + dayNums;
    for (let i = 0; i < arrLen; i++) {
      if (i >= startWeek) {
        num = i - startWeek + 1;
        obj = {
          isToday: '' + year + (month + 1) + num,
          // formateDate: '' + year + '/' + (month > month ? month + 1 : '0' + (month + 1)) + '/' + (num < 10 ? '0' + num : num),
          formateDate: '' + year + '/' + (month >= 9 ? month + 1 : '0' + (month + 1)) + '/' + (num < 10 ? '0' + num : num),
          dateNum: num,
          weight: 5
        }
      } else {
        obj = {};
      }
      dateArr[i] = obj;
    }
    this.setData({
      dateArr: dateArr
    })
    let nowDate = new Date();
    let nowYear = nowDate.getFullYear();
    let nowMonth = nowDate.getMonth() + 1;
    let nowWeek = nowDate.getDay();
    let getYear = setYear || nowYear;
    let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;

    if (nowYear == getYear && nowMonth == getMonth) {
      this.setData({
        isTodayWeek: true,
        todayIndex: nowWeek
      })
    } else {
      this.setData({
        isTodayWeek: false,
        todayIndex: -1
      })
    }
  },
  lastMonth: function() {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
    let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
    this.setData({
      year: year,
      month: (month + 1)
    })
    this.dateInit(year, month);
    this.getData();
  },
  nextMonth: function() {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
    let month = this.data.month > 11 ? 0 : this.data.month;
    this.setData({
      year: year,
      month: (month + 1)
    })
    this.dateInit(year, month);
    this.getData();
  },
  plusclass: function(e) {
    if (e.currentTarget.dataset.oper == 'add') {
      this.addclass();
    }
    if (e.currentTarget.dataset.oper == 'cut') {

      this.cutclass(e.currentTarget.dataset.yindex);
    }
  },
  addclass: function() {
    let temp = this.data.yuekearr;
    temp.push({
      s: "0000-00-00",
      e: "0000-00-00"
    }); //start time ,end time
    this.setData({
      yuekearr: temp,
      plusswitch: true
    });
  },
  cutclass: function(index) {
    for (var a in this.data.classtotal) {
      if (this.data.classtotal[a] == index) {
        delete(this.data.classtotal[a]);
      }
    }

    let temp = this.data.yuekearr;
    temp.splice(index, 1); //start time ,end time
    this.setData({
      plusswitch: false,
      yuekearr: temp,
      startTime: '00:00',
      endTime: '00:00',
    });
  },
  /**
   * 日历控件绑定函数 
   * 点击日期返回
   */
  onPickerChange: function(e) {

    let pickindex = e.currentTarget.dataset.pickindex;
    let picktype = e.currentTarget.dataset.picktype;
    let temparr = this.data.yuekeDataArr;
    let sxname = picktype + e.detail.year.toString() + e.detail.month.toString() + e.detail.day.toString();
    let timestamp = (new Date(e.detail.dateString.replace(/-/g, '/'))).getTime();
    let nowstamp = parseInt((new Date().getTime()) / 60000) * 60000;
    console.log(nowstamp);
    console.log(timestamp);
    if (timestamp < nowstamp) {
      wx.showToast({
        title: '选择的时间必须大于当前时间',
        mask: true,
        duration: 2000,
        icon: 'none'
      })
      if (e.currentTarget.id == "start") {
        let pickcompot = this.selectComponent("#start");
        pickcompot.setData({
          dateString: '请选择时间'
        });
      } else {
        let pickcompot = this.selectComponent("#end");
        pickcompot.setData({
          dateString: '请选择时间'
        });
      }
      return false;
    }
    // start 设置当前的开始课程时间结束课程时间
    if (picktype == "starttime") {
      this.data.curStarday = parseInt(e.detail.day);
      this.data.curStartime = this.string2time(e.detail.dateString);
    } else {
      this.data.curEndday = parseInt(e.detail.day);
      this.data.curEndtime = this.string2time(e.detail.dateString);
    }
    //判断 当前选择的时间是否合法
    if (parseInt(this.data.curEndday) > 0 && parseInt(this.data.curStarday) > 0 && parseInt(this.data.curStarday) != parseInt(this.data.curEndday)) {
      wx.showToast({
        title: '不能跨天选择',
        mask: true,
        duration: 2000,
        icon: 'none'
      })
      this.data.curEndday = 0;
      let pickcompot = this.selectComponent("#end");
      pickcompot.setData({
        dateString: '请选择时间'
      });


    } else if (parseInt(this.data.curEndday) <= 0) {
      let pickcompot = this.selectComponent("#end");
      pickcompot.setData({
        dateString: '请选择时间'
      });
    } else if (parseInt(this.data.curStarday) <= 0) {
      let pickcompot = this.selectComponent("#start");
      pickcompot.setData({
        dateString: '请选择时间'
      });
    } else if (parseInt(this.data.curEndtime) > 0 && parseInt(this.data.curEndtime - this.data.curStartime) < parseInt(this.data.classsc)) {
      this.data.curEndday = 0;
      wx.showToast({
        title: '每次课不能少于两小时',
        mask: true,
        duration: 2000,
        icon: 'none'
      })
      let pickcompot = this.selectComponent("#end");
      pickcompot.setData({
        dateString: '请选择时间'
      });
    } else { //设置开始时间结束时间 并存储传参数组
      if (picktype == "starttime") {
        if (typeof(temparr[pickindex]) == 'undefined') {
          temparr[pickindex] = new Array();
          temparr[pickindex].push(e.detail.dateString);
        } else {
          temparr[pickindex][0] = e.detail.dateString;
        }
        this.data.yuekearr[pickindex].s = e.detail.dateString;
        this.setData({
          yuekearr: this.data.yuekearr
        });
        //this.data.yuekearr[pickindex].uneque = picktype + pickindex.toString();
      }
      if (picktype == "endtime") {
        console.log(123);
        if (typeof(temparr[pickindex]) == 'undefined') {
          temparr[pickindex] = new Array();
          temparr[pickindex].push(['', e.detail.dateString]);
        } else {
          temparr[pickindex].e = e.detail.dateString;
        }

        this.data.yuekearr[pickindex].e = e.detail.dateString;
        this.setData({
          yuekearr: this.data.yuekearr
        });
      }
      this.setData({ //存储传参 传入服务端
        date: e.detail.dateString,
        yuekeDataArr: temparr
      })
      //判断是否同一天越课超过两节
    }
  },
  string2time(str) { //时间字符串转换为时间戳
    let date = str;
    date = date.replace(/-/g, '/');
    let timestamp = new Date(date).getTime();
    return timestamp;

  },

  //获取数据
  getData: function() {
    let that = this;
    if (!this.data.selectDate) {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      this.data.selectDate = year.toString() + '-' + (month > 9 ? month.toString() : "0" + month.toString());
    } else {
      let year = this.data.year;
      let month = this.data.month;
      this.data.selectDate = year.toString() + '-' + (month > 9 ? month.toString() : "0" + month.toString());
    }
    console.log("selctDate:", this.data.selectDate)
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token,
      date: this.data.selectDate
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "user/historynote?sign=" + sign;
    let classPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );
    let classHis = new Object();
    classPro.then(function(res) {
      if (res.data.code === 1) {
        classHis = res.data;
        that.setData({
          confirmed: classHis.data.confirmed,
          confirmles: classHis.data.confirmles,
          justsub: classHis.data.rowfirm
        });
        console.log(that.data.justsub)
      } else if (res.data.code == 10001) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  //提交課程
  dateClass: function() {
    console.log(this.data.yuekearr);
    let that = this;
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token,
      start_time: that.data.paramDate + ' ' + that.data.startTime,
      end_time: that.data.paramDate + ' ' + that.data.endTime
      // start_time: that.data.yuekearr[0].s,
      // end_time: that.data.yuekearr[0].e
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "user/upschedule?sign=" + sign;
    let classPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );
    classPro.then(function(res) {
      if (res.data.code === 1) {
        wx.showToast({
          title: res.data.info,
          icon: "success",
          duration: 2000
        });
        that.cutclass(0);
        that.dataInit();
        that.getData();
        that.getList();
      } else if (res.data.code == 10001) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      } else {
        wx.showToast({
          title: res.data.info,
          icon: "none",
          duration: 2000
        });
      }
    });
  }, //初始化提交数据
  dataInit: function() {
    this.setData({
      curStartime: '',
      curEndtime: '',
      curStarday: '',
      curEndday: '',
    })
  },

  /**时间选择器时间改变 */
  bindTimeChange: function(e) {
    this.setData({
      startTime: e.detail.value
    })
  },

  //结束时间改变
  bindEndTimeChange: function(e) {
    this.setData({
      endTime: e.detail.value
    })
  },

  //点击日历的某个日期的时候
  clickDate: function(e) {
    var that = this;
    var curdate = e.target.dataset.curdate;
    console.log(curdate)
    this.setData({
      paramDate: curdate,
      startTime: '00:00',
      endTime: '00:00',
      isBeforToday: that.contrastTime(curdate),
    })
    that.cutclass(0);
    //获取某天的上课日历
    that.getList();
  },

  // 获取某天的上课日历
  getList: function(e) {
    let listHis = new Object();
    let that = this;
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token,
      date: this.data.paramDate
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "user/history?sign=" + sign;
    let listPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );
    listPro.then(function(res) {
      if (res.data.code == 1) {
        listHis = res.data;
        for (let ele in listHis.data) {
          listHis.data[ele].date = listHis.data[ele].start_time.slice(0, 10);
          listHis.data[ele].start_time = listHis.data[ele].start_time.slice(10);
          listHis.data[ele].end_time = listHis.data[ele].end_time.slice(10);
          switch (parseInt(listHis.data[ele].status)) {
            case 0:
              {
                listHis.data[ele].img = "yueke_icon_daiqueren@2x.png";
                listHis.data[ele].dis = "none";
                break;
              }
            case 1:
              {
                listHis.data[ele].img = "yueke_icon_yiqueren@2x.png";
                listHis.data[ele].dis = "none";
                break;
              }
            default:
              {
                listHis.data[ele].img = "yueke_icon_yitijiao@2x.png";
                listHis.data[ele].dis = "block";
              }
          }
        }
        that.setData({
          classList: listHis.data
        })
      } else if (res.data.code == 10001) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      } else {
        that.setData({
          classList: {}
        })
        wx.showToast({
          title: res.data.info,
          icon: "none"
        })
      }
    })
  },

  //提示是否删除已提交的弹窗
  showDeleteclassModal: function(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '是否确定要删除该约课日期',
      success(res) {
        if (res.confirm) {
          that.deleteclass(e);
        } else if (res.cancel) {

        }
      }
    })
  },

  /**删除已提交的约课  */
  deleteclass: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.yindex;
    let id = e.currentTarget.dataset.id;
    let temp = this.data.classList;
    //删除课程
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token,
      id: id
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "user/delschedule?sign=" + sign;
    let deletePro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );
    deletePro.then(function(res) {
      if (res.data.code === 1) {
        wx.showToast({
          title: res.data.info,
          icon: "success",
          duration: 2000

        });
        temp.splice(index, 1); //start time ,end time
        that.setData({
          classList: temp
        });
      } else if (res.data.code == 10001) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      } else {
        wx.showToast({
          title: res.data.info,
          duration: 2000
        });
      }
      that.getData();
      that.getList();
    });
  },

  //比较时间
  contrastTime(start) {
    var dB = new Date(start.replace(/-/g, "/")); //获取当前选择日期
    var now = new Date();
    var today = now.getFullYear() + "/" + (now.getMonth() + 1) + "/" + now.getDate(); //获取当前实际日期
    if (Date.parse(today) >= Date.parse(dB)) { //时间戳对比
      return true;
    }
    return false;
  }
})